<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;

class CorderController extends Controller
{
    public function index()
    {
        $address=DB::table('address')->where('uid','=',session()->get('homeuser')->id)->get();
        $config=DB::table('config')->get();
        $order=DB::table('car')->join('goods','car.gid','=','goods.id')->where('uid',session()->get('homeuser')->id)->get()->toArray();
        $count=0;
        $alltotal=0;
        for ($i=0; $i < count($order); $i++) {
            // 构造添加到订单表的数据
            $arr=array('uid'=>$order[$i]->uid,'gid'=>$order[$i]->gid,'size'=>$order[$i]->size,'number'=>$order[$i]->num,'gname'=>$order[$i]->goodname,'gprice'=>$order[$i]->price,'total'=>$order[$i]->price*$order[$i]->num);
            $id=DB::table('order')->insertGetId($arr);
            $data[$i]=DB::table('order')->where('id',$id)->get();
            $oid[$i]=$id;
            $count+=$order[$i]->num;
            $alltotal+=$order[$i]->price*$order[$i]->num;
        }

        return view('home.corder',['address'=>$address,'config'=>$config,'data'=>$data,'oid'=>$oid,'count'=>$count,'alltotal'=>$alltotal]);
    }
    public function store(Request $request)
    {
        $info=$request->input('did');
        $data=array('did'=>$info);
        $count=$request->input('count');
        for ($i=0; $i < $count; $i++) {
            $oid=$request->input('oid_'.$i);
            $row = DB::table('order')->where('id',$oid)->update($data);
        }
        $add=DB::table('address')->where('id',$info)->first();
        echo json_encode($add);
    }
    public function update(Request $request)
    {
        $data=array('state'=>'1');
        $count=$request->input('count');
        for ($i=0; $i < $count; $i++) {
            $oid=$request->input('oid_'.$i);
            $row = DB::table('order')->where('id',$oid)->update($data);
            $dingdan[]=DB::table('order')->where('id',$oid)->first();
        }
        $row1=DB::table('order')->where('state','0')->count();
        if ($row1>0) {
            $row2=DB::table('order')->where('state','0')->delete();
        }
        $list=DB::table('type')->get();
        $config=DB::table('config')->get();
        return view('home.pay',['list'=>$list,'config'=>$config,'dingdan'=>$dingdan]);
    }
}
